﻿using System;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalEstimateTaskControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelEstimateTask.ContentTemplateContainer, bstate);
        }

        public void ShowModal(int companyid, int Estimateid, int taskid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Estimate Task";

            if (LoadEstimateTaskDataByID(companyid, Estimateid, taskid))
            {
                btnEditTask.Visible = true;
                btnSaveTask.Visible = false;
                btnDeleteTask.Visible = false;
                SetControlEnabledState(false);
            }
            else
            {
                btnEditTask.Visible = false;
                btnSaveTask.Visible = true;
                btnDeleteTask.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalEstimateTask.Show();
        }
        public bool LoadEstimateTaskDataByID(int companyid, int Estimateid, int taskid)
        {
            bool bHaveData = false;
            int locationid = 0;

            if (companyid > 0 && Estimateid > 0)
            {
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "TASK_CAT", ddlTaskStatus);

                txtEstimateId.Text = Estimateid.ToString();
                locationid = RSSBMCommonFunctions.GetLocationIDByEstimateID(companyid, Estimateid);
                //ucLocationHeaderControl.LoadLocationHeader(companyid, locationid, false, false);
                hfLocationId.Value = locationid.ToString();

                if (taskid > 0)
                {
                    btnDeleteTask.Enabled = true;
                    string strSQL = "SELECT t.TaskId, t.TaskName, t.Description, t.Response, t.StartDT, t.EndDT, t.LaborCost, t.DiscountPercent, t.DiscountAmount,";
                    strSQL = strSQL + " t.EstimateId, t.AssignTo, t.LocationId, t.StatusId, t.CompanyId";
                    strSQL = strSQL + " FROM rs_tblEstimateTask t INNER JOIN rs_tblEstimate p ON t.EstimateId=p.EstimateId WHERE t.EstimateId=@EstimateId AND t.TaskId=@taskid";
                    strSQL = strSQL + " AND t.CompanyId=@CompanyId ORDER BY t.StartDT DESC";

                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Estimateid";
                    param.Value = Estimateid;
                    myCommand.Parameters.Add(param);

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Taskid";
                    param.Value = taskid;
                    myCommand.Parameters.Add(param);

                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        myDataReader.Read();
                        if (myDataReader["LocationId"] != DBNull.Value)
                            locationid = int.Parse(myDataReader["LocationId"].ToString());

                        txtTaskId.Text = taskid.ToString();
                        txtTaskName.Text = myDataReader["TaskName"].ToString();

                        if (myDataReader["StartDT"] != DBNull.Value)
                        {
                            DateTime startdt = Convert.ToDateTime(myDataReader["StartDT"].ToString());
                            txtStartTime.Text = startdt.ToShortTimeString();
                            txtStartDate.Text = startdt.ToShortDateString();
                        }

                        if (myDataReader["EndDT"] != DBNull.Value)
                        {
                            DateTime enddt = Convert.ToDateTime(myDataReader["EndDT"].ToString());
                            txtEndTime.Text = enddt.ToShortTimeString();
                            txtEndDate.Text = enddt.ToShortDateString();
                        }

                        txtDescription.Text = myDataReader["Description"].ToString();
                        txtResponse.Text = myDataReader["Response"].ToString();
                        ddlTaskStatus.SelectedValue = myDataReader["StatusId"].ToString();

                        txtLaborCost.Text = myDataReader["LaborCost"].ToString();
                        txtDiscountPercent.Text = myDataReader["DiscountPercent"].ToString();
                        txtDiscountAmount.Text = myDataReader["DiscountAmount"].ToString();

                        RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                        bHaveData = true;
                    }
                    myConnection.Close();
                }
                

            }
            return bHaveData;
        }


        protected void btnEditTask_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnEditTask.Visible = false;
                btnSaveTask.Visible = true;
                btnDeleteTask.Visible = true;
                SetControlEnabledState(true);
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditTask.Visible = false;
                btnSaveTask.Visible = false;
                btnDeleteTask.Visible = false;
                SetControlEnabledState(false);
            }
        }

        protected void btnSaveTask_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;

                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value); // ucLocationHeaderControl.LocationId;
                int EstimateId = txtEstimateId.Text == "" ? 0 : Convert.ToInt32(txtEstimateId.Text);
                int TaskId = txtTaskId.Text == "" ? 0 : Convert.ToInt32(txtTaskId.Text);

                string TaskName = txtTaskName.Text.Trim();
                string StartDT = txtStartDate.Text + " " + txtStartTime.Text.Trim();
                string EndDT = txtEndDate.Text + " " + txtEndTime.Text.Trim();
                StartDT = StartDT.Trim();
                EndDT = EndDT.Trim();
                string Description = txtDescription.Text.Trim();
                string Response = txtResponse.Text.Trim();

                float LaborCost = txtLaborCost.Text == "" ? 0 : Convert.ToSingle(txtLaborCost.Text);
                int DiscountPercent = txtDiscountPercent.Text == "" ? 0 : Convert.ToInt32(txtDiscountPercent.Text);
                float DiscountAmount = txtDiscountAmount.Text == "" ? 0 : Convert.ToSingle(txtDiscountAmount.Text);

                string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo);
                int StatusID = Convert.ToInt32(ddlTaskStatus.SelectedValue);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskName", SqlDbType.NVarChar, 100, ParameterDirection.Input, TaskName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StartDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, StartDT);

                if (EndDT.Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@EndDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, EndDT);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Money, 0, ParameterDirection.Input, LaborCost);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountPercent", SqlDbType.SmallInt, 0, ParameterDirection.Input, DiscountPercent);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountAmount", SqlDbType.Money, 0, ParameterDirection.Input, DiscountAmount);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskID", SqlDbType.Int, 0, ParameterDirection.Input, TaskId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EstimateId", SqlDbType.Int, 0, ParameterDirection.Input, EstimateId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveEstimateTask");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Task successfully saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                hfRedirectURL.Value = "";
             }
            btnEditTask.Visible = false;
            btnSaveTask.Visible = false;
            btnDeleteTask.Visible = false;
            SetControlEnabledState(false);
        }
        protected void btnDeleteTask_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int TaskId = txtTaskId.Text == "" ? 0 : Convert.ToInt32(txtTaskId.Text);
                int EstimateId = txtEstimateId.Text == "" ? 0 : Convert.ToInt32(txtEstimateId.Text);

                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskId", SqlDbType.Int, 0, ParameterDirection.Input, TaskId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EstimateId", SqlDbType.Int, 0, ParameterDirection.Input, EstimateId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

                SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblEstimateTask WHERE EstimateId=@EstimateId AND TaskId=@TaskId AND CompanyId=@CompanyId");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Task successfully removed from Estimate!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                hfRedirectURL.Value = "";
            }
            btnEditTask.Visible = false;
            btnSaveTask.Visible = false;
            btnDeleteTask.Visible = false;
            SetControlEnabledState(false);
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
            {
                var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                nameValues.Set("tabindex", "1");
                string url = Request.Url.AbsolutePath;
                string updatedQueryString = "?" + nameValues.ToString();
                Response.Redirect(url + updatedQueryString);
            }
            else
            {
                mpeModalEstimateTask.Hide();
            }
        }
        
    }

    
}